package com.neuedu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.myUtil.JwtUtil;
import com.neuedu.pojo.Permission;
import com.neuedu.pojo.User;
import com.neuedu.service.IPermissionService;
import com.neuedu.util.CommonResult;
import com.neuedu.util.InitUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * <p>
 * 权限 前端控制器
 * </p>
 *
 * @author liuyong
 * @since 2020-09-17
*/
@RestController
@RequestMapping("/permissions")
public class PermissionController {
    private final Logger logger = LoggerFactory.getLogger(PermissionController.class);

    @Resource
    private IPermissionService iPermissionService;

    /**
     * 进行分页查询
     */
    @GetMapping("/list")
    public CommonResult getList(@RequestParam Map<String, Object> param) {
        InitUtil.initPage(param);
        int num = Integer.parseInt(param.get("page").toString());
        int limit = Integer.parseInt(param.get("limit").toString());
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        InitUtil.initEq(param, wrapper, "active");
        IPage<Permission> page = new Page<>(num, limit);
        return CommonResult.success(iPermissionService.page(page, wrapper));
    }

    /**
     * 获取树形的权限树
     */
    @GetMapping
    public CommonResult getlistByTree() {
        return CommonResult.success(iPermissionService.listByTree());
    }

    /**
     * 通过主键id在表中查找信息
     */
    @GetMapping("/{id}")
    public CommonResult getById(@PathVariable int id) {
        Permission iPermission = iPermissionService.getById(id);
        if (iPermission == null) {
            return CommonResult.failed();
        }
        return CommonResult.success(iPermission);
    }

    /**
     * name : 需要检查那个字段的value是否在数据库存在
     * 比如/check/RegistworkName?value=阿司匹林  ：检查数据库是否存在RegistworkName='阿司匹林'
     */
    @GetMapping("/check/{name}")
    public CommonResult checkName(@PathVariable String name,@RequestParam String value){
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq(name, value);
        if (iPermissionService.getOne(wrapper) != null){
            return CommonResult.failed();
        }
        return CommonResult.success();
    }

    /**
     * 根据用户的角色类型获取菜单
     */
    @GetMapping("/userPermissionList")
    public CommonResult userPermissionList(HttpServletRequest request){
        String token = request.getHeader("Authorization");// 从 http 请求头中取出 token
        logger.debug("/userPermissionList:  "+token);
        User user = JwtUtil.getUserById(token);
        return CommonResult.success(iPermissionService.userPermissionList(user.getId()));
    }

    /**
     * 向表中添加一条记录
     */
    @PostMapping()
    public CommonResult save(@RequestBody Permission iPermission) {
        if (iPermissionService.save(iPermission)){
            return CommonResult.successMsg("添加成功");
        }
        return CommonResult.failed("添加失败");
    }

    /**
     * 根据表中的主键修改 根据表中字段相应的修改，如果存在则修改
     */
    @PutMapping("/{id}")
    public CommonResult update(@RequestBody Permission iPermission, @PathVariable int id) {
        iPermission.setId(id);
        if (iPermissionService.updateById(iPermission)){
            return CommonResult.successMsg("修改成功");
        }
        return CommonResult.failed("修改失败");
    }

    /**
     * active 字段 相当于激活一样 设置字段的有效性 active=1 有效
     */
    @PutMapping("/back/{id}")
    public CommonResult update(@PathVariable int id) {
        Permission iPermission = new Permission();
        iPermission.setId(id);
        iPermission.setActive(1);
        if (iPermissionService.updateById(iPermission)){
            return CommonResult.successMsg("激活成功");
        }
        return CommonResult.failed("激活失败");
    }

    /**
     * active 字段 相当于激活一样 设置字段的有效性 active=0 无效 逻辑删除
     */
    @PutMapping("/del/{id}")
    public CommonResult LoginDelById(@PathVariable int id) {
        Permission iPermission = new Permission();
        iPermission.setId(id);
        iPermission.setActive(0);
        if (iPermissionService.updateById(iPermission)){
            return CommonResult.successMsg("设置失效成功");
        }
        return CommonResult.failed("设置失效失败");
    }

    /**
     * 批量设置 active=0
     */
    @PutMapping("/batchDel")
    public CommonResult LoginBatchDel(@RequestParam String ids) {
        Permission iPermission = new Permission();
        iPermission.setActive(0);
        String[] idList = ids.split(",");
        for (String id : idList) {
            iPermission.setId(Integer.parseInt(id));
            iPermissionService.updateById(iPermission);
        }
        return CommonResult.successMsg("批量失效成功");
    }

    /**
     * 在数据表中真正的删除一条记录
     */
    @DeleteMapping("/{id}")
    public CommonResult delById(@PathVariable int id) {
        if (id<20) {
            return CommonResult.failed("不能删除系统的预留项");
        }
        logger.debug("正在删除id: "+id);
        if (iPermissionService.removeById(id)){
            return CommonResult.successMsg("删除成功");
        }
        return CommonResult.failed("删除失败");
    }

}
